package com.ruoyi.system.xmlAbstract.interfaces.analysisInterfaces.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ruoyi.system.xmlAbstract.XmlGenerateAbstract;
import com.ruoyi.system.xmlAbstract.dto.XmlNodeBuildDto;
import com.ruoyi.system.xmlAbstract.interfaces.analysisInterfaces.XmlTemplateAnalysis;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import java.util.UUID;

/**
 * @author : anxinr
 * @date : 2023/8/17 18:14
 */
public class H5XmlAnalysis implements XmlTemplateAnalysis {

    /**后解析堆栈映射*/
    public Map<String,Stack<XmlNodeBuildDto>> map = new HashMap<>() ;

    @Override
    public void analysisXmlTemplate(XmlGenerateAbstract xmlTemplate) throws Exception {
        /**解析的XML数据*/
        StringBuilder xml = xmlTemplate.xml;
        /**要解析的数据*/
        XmlNodeBuildDto rootXmlNode = xmlTemplate.rootXmlNode;
        /**正向解析*/
        forwardAnalysisXmlTree(rootXmlNode, xml) ;
    }

    private void LIFOAnalysisXmlTree(String mapId,StringBuilder xml) {
        Stack<XmlNodeBuildDto> stack = map.get(mapId);
        if (stack.size() != 0){
            int size = stack.size();
            for (int i = 0; i < size; i++) {
                XmlNodeBuildDto pop = stack.pop();
                xml.append(pop.generateHeadEnd()) ;
            }
        }
    }

    private void forwardAnalysisXmlTree(XmlNodeBuildDto rootXmlNode, StringBuilder xml) throws Exception {
        recursionXmlTree(rootXmlNode, xml) ;
    }

    private void recursionXmlTree(XmlNodeBuildDto rootXmlNode, StringBuilder xml) throws Exception {
        /**解析node标题*/
        if (StringUtils.isNotBlank(rootXmlNode.getXmlNode())){
            xml.append(rootXmlNode.generateH5Head()) ;
        }
        if (CollectionUtil.isNotEmpty(rootXmlNode.getList())){
            Stack<XmlNodeBuildDto> stack = new Stack<>();
            /**映射 key */
            String key = UUID.randomUUID().toString() ;
            stack.push(rootXmlNode) ;
            map.put(key,stack) ;
            for (XmlNodeBuildDto xmlNodeBuildDto : rootXmlNode.getList()) {
                /**递归遍历 生成标签*/
                recursionXmlTree(xmlNodeBuildDto,xml);
            }
            /**模板堆栈  后进先出解析*/
            LIFOAnalysisXmlTree(key,xml) ;
        }else {
            /**如果没有子节点 则直接拼接结束标签*/
            xml.append(rootXmlNode.generateHeadEnd()) ;
        }
    }
}
